package edc;

/**
 *
 * @author sasheto
 */
public class ParityCheckCode extends Code {
    public static final int WORD_LENGHT = 7;

    // TODO: implement
    public ParityCheckCode(String data) {
        super(data);
    }

    @Override
    protected String encodeData() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public String generateEvenParityCheck() {
        String data = super.getData();
        int[] bytes = new int[data.length()];
        int codedDataLenght = calculateCodedDataArrayLenght(bytes);
        int[] codedData = new int[codedDataLenght];

        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = Integer.parseInt(data.substring(i, i + 1));
        }
        reverseArray(bytes);

        byte counterFor1 = 0;
        byte bitCounter = 0;
        byte checkBitCounter = 0;

        for (int i = 0; i < bytes.length + checkBitCounter; i++) {
            if (bitCounter == WORD_LENGHT) {
                if (counterFor1 % 2 == 0) {
                    codedData[i] = 0;
                } else {
                    codedData[i] = 1;
                }
                checkBitCounter++;
                counterFor1 = 0;
                bitCounter = 0;
            } else {
                if (bytes[i - checkBitCounter] == 1) {
                    counterFor1++;
                }
                codedData[i] = bytes[i - checkBitCounter];
                bitCounter++;
            }
        }

        if (counterFor1 % 2 != 0) {
            codedData[codedData.length - 1] = 1;
        }

        StringBuilder resultBuilder = new StringBuilder();
        for (int i = codedData.length - 1; i >= 0; i--) {
            resultBuilder.append(codedData[i]);
        }
        return resultBuilder.toString();
    }

    private void reverseArray(int[] bytes) {
        int[] temp = new int[bytes.length];
        for (int i = 0; i < bytes.length; i++) {
            temp[bytes.length - 1 - i] = bytes[i];
        }
        System.arraycopy(temp, 0, bytes, 0, bytes.length);
    }

    private int calculateCodedDataArrayLenght(int[] bytes) {
        int resultArrayLenght = 0;
        resultArrayLenght = bytes.length + bytes.length % WORD_LENGHT;
        if (bytes.length % WORD_LENGHT != 0) {
            resultArrayLenght = resultArrayLenght + WORD_LENGHT + 1 - (bytes.length % WORD_LENGHT);
        }
        return resultArrayLenght;
    }
}
